import { Component, OnInit } from '@angular/core';
import {AbstractControl, FormControl, FormGroup, NonNullableFormBuilder, ValidatorFn, Validators} from "@angular/forms";
import {NzFormTooltipIcon} from "ng-zorro-antd/form";
import {HttpService} from "../../service/http/http.service";
import {NzMessageService} from "ng-zorro-antd/message";

@Component({
  selector: 'app-shop',
  templateUrl: './shop.component.html',
  styleUrls: ['./shop.component.scss']
})
export class ShopComponent implements OnInit {

  okLoading = false;
  tableLoading = false;
  listOfData: any[] = [];
  page = 1;
  size = 10;
  total = 0;
  validateForm: FormGroup<{
    id:FormControl<number>;
    name: FormControl<string>;
    payMoney:FormControl<string>;
  }>;


  constructor(private fb: NonNullableFormBuilder,
              private msg:NzMessageService,
              private http:HttpService) {
    this.validateForm = this.fb.group({
      id: [0],
      name: ['', [Validators.required]],
      payMoney: ['', [Validators.required]],
    });
  }


  ngOnInit() {

    this.getList();
  }



  getList(){

    let params = {
      pageNumber:this.page,
      pageSize:this.size
    }
    this.tableLoading = true;
    let url = "/shop/list";
    this.http.get(url,params).then((res:any)=>{
      this.tableLoading = false;
      this.listOfData = res.records;
      this.total = res.total;
    }).catch(err=>{
      this.tableLoading = false;
    });
  }

  isVisible = false;
  add(){
    this.isEdit = false;
    this.isVisible = true;
    this.validateForm.reset();
  }

  handleCancel(){
    this.isVisible = false;
  }

  deletedUser(item:any){
    let url = "/shop/deleted"
    this.http.get(url,{id:item.id}).then(res=>{
      this.msg.success("删除成功");
      this.getList();
    }).catch(err=>{
      this.msg.error(err);
    });
  }

  changePage(p:any){
    this.page = p;
    this.getList();
  }

  private isEdit = false;
  edit(data:any){
    console.log(data);
    this.validateForm.reset({
      id:data.id,
      name: data.name,
      payMoney:data.payMoney
    });
    this.isEdit = true;
    this.isVisible = true;
  }

  handleOk(){
    if (this.validateForm.valid) {
      let value = this.validateForm.value;
      let url = "/shop/add"
      if (this.isEdit){
        url = "/shop/edit"
      }
      this.okLoading = true;
      this.http.postBody(url,value).then(res=>{
        this.okLoading = false;
        this.isVisible = false;
        if (this.isEdit){
          this.msg.success("修改成功");
        }else {
          this.msg.success("添加成功");
        }
        this.getList();
      }).catch(err=>{
        this.okLoading = false;
        this.msg.error(err);
      });
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }

  }

}
